<?php

/**
 * 商家- 产品　控制器
 *
 * @author liminghui
 */

require_once 'CommonController.php';

class Admin_PartnerProductController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_PartnerProduct();
        $this->view->title = "管理中心";
        $this->username = Application_Model_UserLogin::getInstance()->getLoginedUserName();
    }

    /**
     * 商家－产品　信息管理（mob_partner_product）
     * 
     * @return void
     */
    public function indexAction()
    {
        $partnerModel = new Application_Model_Partner();

        //取得partner表里的商家信息
        $partnerRow = $partnerModel->fetchAll(NULL, "addTime DESC");
        $this->view->partnerRow = $partnerRow;

        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['partnerCode'] = trim($this->_request->get('partnerCode'));
        $vars['code'] = trim($this->_request->get('code'));
        $vars['name'] = trim($this->_request->get('name'));
        $urls = $vars;

        if ($vars['partnerCode'] != '') {
            $wheres[] = "`pp`.`partnerCode` = '{$vars['partnerCode']}'";
        }
        if ($vars['code'] != '') {
            $wheres[] = "`pp`.`code` LIKE '%" . addslashes($vars['code']) . "%'";
        }
        if ($vars['name'] != '') {
            $wheres[] = "`pp`.`name` LIKE '%" . addslashes($vars['name']) . "%'";
        }
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "
            SELECT `pp`.*,`p`.`name` AS `partnerName` FROM `{$this->_model->getTableName()}` AS `pp` 
            LEFT JOIN `{$partnerModel->getTableName()}` AS `p` ON `p`.`code` = `pp`.`partnerCode`
            {$where} 
            ORDER BY `pp`.`id` DESC
        ";

        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        $rows = $dbPaginator->getRows();

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
    }
    
    /**
     * 删除产品
     * 
     * @return void
     */
    public function deleteAction(){
        //角色
        $partnerProductModel = new Application_Model_PartnerProduct();
        $backUrl = trim($this->_request->get('backUrl'));//返回的url
        
        if ($this->_request->isPost()) {
            $groupIdArr = $this->_request->get('selectId');
            if (!empty($groupIdArr)) {
                foreach ($groupIdArr as $id) {
                    $row = $partnerProductModel->fetchRow("`id` = {$id}");
                    if (!empty($row)) {
                        $res = $partnerProductModel->delete("`id` = {$id}");
                        if(!$res){
                            exit($this->view->message('删除失败！',  $backUrl));
                        }
                    } else {
                        exit($this->view->message('数据不存在！',  $backUrl));
                    }
                }
            } else {
                exit($this->view->message('请选择相应参数！',  $backUrl));
            }
            
        } else {//暂时不做级联删除
            $id = trim($this->_request->get('id'));
            $row = $partnerProductModel->fetchRow("`id` = {$id}");
            if (!empty($row)) {
                $res = $partnerProductModel->delete("`id` = {$id}");
                if (!$res) {
                    exit($this->view->message('删除失败！', $backUrl));
                }
            } else {
                exit($this->view->message('数据不存在！', $backUrl));
            }
        }
        
        exit($this->view->message('删除成功！', $backUrl));
        
    }

    /**
     * 修改产品信息
     * 
     * @return void
     */
    public function updateAction()
    {
        $partnerProductManagerModel = new Application_Model_PartnerProductManager();
        $partnerModel = new Application_Model_Partner();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $partnerRow = $partnerModel->fetchAll(NULL, "addTime DESC");
        $this->view->partnerRow = $partnerRow;
        //取得partner表里的商家信息
        $filter = new Zend_Filter_StripTags();
        $vars['id'] = intval($this->_request->get('id')); 
        $this->view->currVars = $this->_model->fetchRow("id={$vars['id']}");
        $vars['backUrl'] = $filter->filter(trim($this->_request->getPost('backUrl')));
        //提交表单的处理　
        if ($this->_request->isPost()) {
            //取得参数
            $id = intval($filter->filter(trim($this->_request->getPost('id'))));
            $vars['code'] = $filter->filter(trim($this->_request->getPost('code')));
            $vars['name'] = $filter->filter(trim($this->_request->getPost('name')));
            $vars['manager'] = $filter->filter(trim($this->_request->getPost('manager')));
            $vars['comm'] = $filter->filter(trim($this->_request->getPost('comm')));
            $vars['type'] = intval($filter->filter(trim($this->_request->getPost('type'))));
            $vars['isSendReport'] = intval($filter->filter(trim($this->_request->getPost('isSendReport'))));
            $vars['reportMail'] = $filter->filter(trim($this->_request->getPost('reportMail')));
            $vars['sendReportMail'] = $filter->filter(trim($this->_request->getPost('sendReportMail')));
            $vars['udidIsSendReport'] = intval($filter->filter(trim($this->_request->getPost('udidIsSendReport'))));
            $vars['udidReportMail'] = $filter->filter(trim($this->_request->getPost('udidReportMail')));
            $vars['udidSendReportMail'] = $filter->filter(trim($this->_request->getPost('udidSendReportMail')));
            if(!empty($vars['manager'])) {
                $manArr = array_filter(explode(',', $vars['manager']));
                $userModel = new Application_Model_User();
                $managerRows = $userModel->fetchAll(" `userName` in ('" . implode("','", $manArr) . "')");
                $managerTmp = array();
                $checkArr = array();
                foreach($managerRows as $item) {
                    $managerTmp[] = $item['userName'];
                }
                $checkArr = array_diff($manArr, $managerTmp);
                if(!empty($checkArr)) {
                    $checkView = implode(',', $checkArr);
                    exit($this->view->message('运营经理' . $checkView . '不存在！', $this->view->projectUrl( $vars )));
                }
                $partnerProductManagerModel->delete(" `partnerProductCode` = '".$vars['code']."'");
                if(!empty($vars['comm'])) {
                    $commArr = array_filter(explode(',', $vars['comm']));
                    $commRows = $userModel->fetchAll(" `userName` in ('" . implode("','", $commArr) . "')");
                    $commTmp = array();
                    $checkCommArr = array();
                    foreach($commRows as $item) {
                        $commTmp[] = $item['userName'];
                    }
                    $checkCommArr = array_diff($commArr, $commTmp);
                    if(!empty($checkCommArr)) {
                        $checkCommView = implode(',', $checkCommArr);
                        exit($this->view->message('运营专员' . $checkCommView . '不存在！', $this->view->projectUrl( $vars )));
                    }
                    foreach($commArr as $item) {
                        $dataComm['partnerProductCode'] = $vars['code'];
                        $dataComm['type'] = 2;
                        $dataComm['userName'] = $item;
                        $dataComm['addTime'] = date('Y-m-d H:i:s');
                        $dataComm['addUserName'] = $this->username;
                        $partnerProductManagerModel->insert($dataComm);
                    }
                }
                foreach($manArr as $item) {
                    $dataManager['partnerProductCode'] = $vars['code'];
                    $dataManager['type'] = 1;
                    $dataManager['userName'] = $item;
                    $dataManager['addTime'] = date('Y-m-d H:i:s');
                    $dataManager['addUserName'] = $this->username;
                    $partnerProductManagerModel->insert($dataManager);
                }
            }
            $params = array(
                'name' => $vars['name'],
            	'type' => $vars['type'],
            	'isSendReport' => $vars['isSendReport'],
                'reportMail' => $vars['reportMail'],
                'sendReportMail' => $vars['sendReportMail'],
            	'udidIsSendReport' => $vars['udidIsSendReport'],
                'udidReportMail' => $vars['udidReportMail'],
                'udidSendReportMail' => $vars['udidSendReportMail']
            );
            $partnerProductModel->update($params, "`id`='" . $id . "'");
            exit($this->view->message('修改成功！', $this->view->projectUrl(array('action'=>'index'))));
        }
        if (empty($vars['id'])) {
            exit($this->view->message('id不能为空！', $this->view->projectUrl( $vars )));
        }
        $rowAr = $partnerProductModel->filterData(array('id'=> $vars['id']));
        if(empty($rowAr)) {
            exit($this->view->message('记录不存在！', $this->view->projectUrl( $vars )));
        }
        $this->view->partnerProdcutRow = $rowAr;
        $partnerRow = $partnerModel->fetchAll();
        $this->view->partnerRow = $partnerRow;
        $partnerProductManComm = $partnerProductManagerModel->fetchAll(" `partnerProductCode` = '" . $rowAr['code'] . "'");
        
        $partnerProductManager = array();
        $commvTmp = array();
        $manvTmp = array();
        foreach($partnerProductManComm as $item) {
            if($item['type'] == 1) {
                $manvTmp[] = $item['userName'];
            }
            if($item['type'] == 2) {
                $commvTmp[] = $item['userName'];
            }
        }
        $partnerProductManager = array(
                                    'manager' => implode(',', $manvTmp),
                                    'comm' => implode(',', $commvTmp)
                                 );
        $this->view->partnerProductManager = $partnerProductManager;
        
    }
    /**
     * 添加产品信息
     * 
     * @return void
     */
    public function insertAction()
    {
        //角色
        $platformArr = $this->_configs['project']['platform'];
        $this->view->platformArr = $platformArr;
        $partnerModel = new Application_Model_Partner();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $partnerRow = $partnerModel->fetchAll(NULL, "addTime DESC");
        $this->view->partnerRow = $partnerRow;
        $filter = new Zend_Filter_StripTags();
        $vars['partnerCode'] = $filter->filter(trim($this->_request->getPost('partnerCode')));
        $vars['code'] = $filter->filter(trim($this->_request->getPost('code')));
        $vars['name'] = $filter->filter(trim($this->_request->getPost('name')));
        $vars['backUrl'] = $filter->filter(trim($this->_request->getPost('backUrl')));
        $vars['manager'] = $filter->filter(trim($this->_request->getPost('manager')));
        $vars['comm'] = $filter->filter(trim($this->_request->getPost('comm')));
        $vars['type'] = intval($filter->filter(trim($this->_request->getPost('type'))));
        $vars['isSendReport'] = intval($filter->filter(trim($this->_request->getPost('isSendReport'))));
        $vars['reportMail'] = $filter->filter(trim($this->_request->getPost('reportMail')));
        $vars['sendReportMail'] = $filter->filter(trim($this->_request->getPost('sendReportMail')));
        $vars['udidIsSendReport'] = intval($filter->filter(trim($this->_request->getPost('udidIsSendReport'))));
        $vars['udidReportMail'] = $filter->filter(trim($this->_request->getPost('udidReportMail')));
        $vars['udidSendReportMail'] = $filter->filter(trim($this->_request->getPost('udidSendReportMail')));
            
        $platformSel = $this->_request->get('platform');
        //提交表单的处理　
        if ($this->_request->isPost()) {
            //取得参数
            if ($vars['partnerCode'] == '') {
                exit($this->view->message('商家名称不能为空！', $this->view->projectUrl( $vars )));    
            }
            if ($vars['code'] == '') {
                exit($this->view->message('产品编号不能为空！', $this->view->projectUrl( $vars )));    
            }
            //判断code的唯一性，若数据库已经存在此code值，则提示错误
            $codeExist = $partnerProductModel->fetchRow("`code` = '{$vars['code']}'");
            if (!empty($codeExist)) {
                exit($this->view->message('此条产品编号已经存在！', $this->view->projectUrl( $vars )));    
            }
            if(!empty($vars['manager'])) {
                $partnerProductManagerModel = new Application_Model_PartnerProductManager();
                $manArr = array_filter(explode(',', $vars['manager']));
                $userModel = new Application_Model_User();
                $managerRows = $userModel->fetchAll(" `userName` in ('" . implode("','", $manArr) . "')");
                $managerTmp = array();
                $checkArr = array();
                foreach($managerRows as $item) {
                    $managerTmp[] = $item['userName'];
                }
                $checkArr = array_diff($manArr, $managerTmp);
                if(!empty($checkArr)) {
                    $checkView = implode(',', $checkArr);
                    exit($this->view->message('运营经理' . $checkView . '不存在！', $this->view->projectUrl( $vars )));
                }

                if(!empty($vars['comm'])) {
                    $commArr = array_filter(explode(',', $vars['comm']));
                    $commRows = $userModel->fetchAll(" `userName` in ('" . implode("','", $commArr) . "')");
                    $commTmp = array();
                    $checkCommArr = array();
                    foreach($commRows as $item) {
                        $commTmp[] = $item['userName'];
                    }
                    $checkCommArr = array_diff($commArr, $commTmp);
                    if(!empty($checkCommArr)) {
                        $checkCommView = implode(',', $checkCommArr);
                        exit($this->view->message('运营专员' . $checkCommView . '不存在！', $this->view->projectUrl( $vars )));
                    }
                    foreach($commArr as $item) {
                        $dataComm['partnerProductCode'] = $vars['code'];
                        $dataComm['type'] = 2;
                        $dataComm['userName'] = $item;
                        $dataComm['addTime'] = date('Y-m-d H:i:s');
                        $dataComm['addUserName'] = $this->username;
                        $partnerProductManagerModel->insert($dataComm);
                    }
                }

                foreach($manArr as $item) {
                    $dataManager['partnerProductCode'] = $vars['code'];
                    $dataManager['type'] = 1;
                    $dataManager['userName'] = $item;
                    $dataManager['addTime'] = date('Y-m-d H:i:s');
                    $dataManager['addUserName'] = $this->username;
                    $partnerProductManagerModel->insert($dataManager);
                }
            }
            
            $params = array(
                'partnerCode' => $vars['partnerCode'],
                'code' => $vars['code'],
                'name' => $vars['name'],
            	'type' => $vars['type'],
                'isSendReport' => $vars['isSendReport'],
                'reportMail' => $vars['reportMail'],
                'sendReportMail' => $vars['sendReportMail'],
                'udidIsSendReport' => $vars['udidIsSendReport'],
                'udidReportMail' => $vars['udidReportMail'],
                'udidSendReportMail' => $vars['udidSendReportMail']
            );
            $partnerProductModel->insert($params);
            if(!empty($platformSel)){
                $partnerProductPlatformModel = new Application_Model_ProductPlatform();
                foreach($platformSel as $item) {
                    $data['partnerCode'] = $vars['partnerCode'];
                    $data['productCode'] = $vars['code'];
                    $data['osName'] = $item;
                    $data['addTime'] = date("Y-m-d H:i:s");
                    $partnerProductPlatformModel->insert($data);
                }
            }
            exit($this->view->message('添加成功！', $this->view->projectUrl(array('action'=>'index'))));
        }
        $this->view->vars = $vars;//参数
    }
    /**
     * 
     * 批量修改邮件地址 
     * return void
     */
    public function changeMailAction() 
    {
    	$id = intval($this->_request->get('id'));
        $this->view->subtitle='批量修改日报收件地址';
        $this->view->products = $this->_model->fetchAll();
        if ($this->_request->isPost()) {
            $row = array();
            $filter = new Zend_Filter_StripTags();
            $row['email'] = $filter->filter(trim($this->_request->getPost('email')));
            foreach ($_REQUEST['products'] as $id) {
            	$row['id'][] = $id;
            }
            $row['type'] = intval($filter->filter(trim($this->_request->getPost('type'))));
            
            if (strlen($row['email']) < 1) {
                echo $this->view->message('邮件长度不能小于1，请重新填写！') ;
                exit;
            }
         	if (!preg_match("/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@[a-z0-9]+([-_]?[a-z0-9]+)*(\.[a-z-0-9]{1,10})+$/i", $row['email'])) {
                    echo $this->view->message('E-Mail地址填写错误。') ;
                    exit;
            }
            if ($row['type']==0) {
            	echo $this->view->message('必须选择类型，请重新填写。') ;
                exit; 
            }     
            if (count($row['id']) == 0) {
                echo $this->view->message('没有选择任何产品，请重新选择！');
                exit; 
            }
            $this->_model->changeEmail($row);
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'index'))) ;
            exit;
        }
    }
}